package org.exampledriven;


import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class IdGeneratorSnowflake {
    private long workId = 0;
    private long datacenterId = 1;
    private Snowflake snowflake = IdUtil.createSnowflake(workId,datacenterId);

    @PostConstruct
    public void init(){
        try {
            log.info("iphoststr:"+NetUtil.getLocalhostStr());
            workId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("workId:"+workId);
        } catch (Exception exception) {
            exception.printStackTrace();
            workId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public synchronized long snowflakeId(){
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workId,datacenterId);
        return snowflake.nextId();
    }

    public synchronized long snowflakeId(long workId){
        Snowflake snowflake = IdUtil.createSnowflake(workId,datacenterId);
        return snowflake.nextId();
    }
}
